package org.springframework.prospring.ticket.dao.hibernate;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.prospring.ticket.dao.ClubDAO;
import org.springframework.prospring.ticket.domain.Field;
import org.springframework.prospring.ticket.domain.Club;
import org.springframework.prospring.ticket.domain.Turn;
import org.springframework.prospring.ticket.domain.user.User;
import org.springframework.prospring.ticket.exception.BusinessException;
import org.springframework.prospring.ticket.common.Constant;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;

import java.util.*;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.sql.Timestamp;

/**
 * This class interacts with Spring and Hibernate to save and
 * retrieve User objects.
 *
 * @author Alexis Quiros
 */
public class ClubDAOHibernate extends HibernateDaoSupport implements ClubDAO {
    private static Log log = LogFactory.getLog(ClubDAOHibernate.class);

    public ClubDAOHibernate() {
        super();
        if (ClubDAOHibernate.log.isDebugEnabled()) {
            ClubDAOHibernate.log.debug("in ClubDAOHibernate Constructor");
        }
    }

    public Club findClub(Long clubId) {
        if (ClubDAOHibernate.log.isDebugEnabled()) {
            ClubDAOHibernate.log.debug("finding Club id: " + clubId);
        }

        Club club = (Club)getHibernateTemplate().load(Club.class, clubId);

        return club;
    }


    public Collection<Club> findAllClubs() {
        if (ClubDAOHibernate.log.isDebugEnabled()) {
            ClubDAOHibernate.log.debug("finding all Clubs ");
        }

        Collection<Club> clubs = getHibernateTemplate().find("from Club");
        return clubs;
    }

    public Collection<Club> findAllClubsByRegionId(Long regionId) {
        if (ClubDAOHibernate.log.isDebugEnabled()) {
            ClubDAOHibernate.log.debug("finding all Clubs by region id="+regionId);
        }

        String []paramsNames = new String[] {"regionId"};
        Object []paramsValues = new Object[] {regionId};
        Collection<Club> clubs = getHibernateTemplate().findByNamedQueryAndNamedParam("findAllClubs.By.RegionId", paramsNames, paramsValues);
        return clubs;
    }


    public Collection<Field> findFields(Long clubId) {
        Club club = findClub(clubId);
        return club.getFields();
    }

    public Collection<Turn> findAllTurnsByFieldIdAndDate(Long fieldId, Date date){
        SimpleDateFormat dateFormat = new SimpleDateFormat(Constant.DATE_FORMAT_KEY);
        String dateString = dateFormat.format(date);



        Date startDate = null;
        try {
            startDate = dateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        Date endDate = calendar.getTime();

        String [] paramsNames = new String[] {"fieldId", "startDate", "endDate"};
        Object [] paramsValues = new Object[] {fieldId, startDate, endDate};
        List<Turn> turnList = getHibernateTemplate().findByNamedQueryAndNamedParam("findAllTurns.by.fieldId.and.date", paramsNames, paramsValues);

        System.out.println("turnList = " + turnList);

        return turnList;
    }




    public Turn saveReservationField(Long fieldId, Timestamp startDate, Timestamp endDate, User user) {
        if (logger.isDebugEnabled()) {
            logger.debug("making reservation for field id: " + fieldId);
        }

        Turn turn = new Turn();

        turn.setPrice(Float.valueOf("89.0"));
        turn.setSettlement(Float.valueOf("0"));
        turn.setStartDate(startDate);
        turn.setEndDate(endDate);
        turn.setActualDate(new Timestamp(System.currentTimeMillis()));
        turn.setAvailable(Boolean.FALSE);
        turn.setUser(user);


        Field field = (Field) getHibernateTemplate().get(Field.class, fieldId);

        field.addTurn(turn);

        getHibernateTemplate().saveOrUpdate(field);

        return turn;
    }

    public void saveClub(Club club) throws Exception {
        if (ClubDAOHibernate.log.isDebugEnabled()) {
            ClubDAOHibernate.log.debug("Saving Club: " + club);
        }

        if (StringUtils.isEmpty(club.getName())) {
            String message = "The name is required, name="+club.getName();
            ClubDAOHibernate.log.info(message);
            throw new BusinessException(message);
        }

        getHibernateTemplate().saveOrUpdate(club);

        if (ClubDAOHibernate.log.isDebugEnabled()) {
            ClubDAOHibernate.log.debug("clubId set to: " + club.getId());
        }
    }

    public void removeClub(Long clubId) {
        if (ClubDAOHibernate.log.isDebugEnabled()) {
            ClubDAOHibernate.log.debug("removing Club id: " + clubId);
        }

        Object club = getHibernateTemplate().load(Club.class, clubId);
        getHibernateTemplate().delete(club);
    }


}
